package com.huangbiao.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyShiroRealm extends AuthorizingRealm {

	private IShiroService shiroService;
	
	

	/**
	 * @param shiroService the shiroService to set
	 */
	public void setShiroService(IShiroService shiroService) {
		this.shiroService = shiroService;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		// 通过表单接收的用户名，调用currentUser.login的时候执行
		String username = userToken.getUsername();
		if (username != null && !"".equals(username)) {
			// 查询密码
			String password = shiroService.getPasswordByUserName(username);
			if (password != null) {
				return new SimpleAuthenticationInfo(username, password, getName());
			}
		}
		
		return null;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator().next();
		if (username != null) {
			List<String> perms = shiroService.getPermissionByUserName(username);
			List<String> roles = shiroService.getRoleByUserName(username);
			if (perms != null && !perms.isEmpty()) {
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				Set<String> sets = new HashSet<String>();
				for(String role:roles){
					sets.add(role);
				}
				info.setRoles(sets);
				for (String each : perms) {
					// 将权限资源添加到用户信息中
					info.addStringPermission(each);
				}
				return info;
			}
		}
		return null;
	}

}
